package cloud.xlh.infrastructure.utils;

import lombok.extern.slf4j.Slf4j;
import org.jumpmind.symmetric.csv.CsvReader;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2022/11/27 18:48
 * @ Description:
 */
@Slf4j
public class StringUtil {

    /** 空字符串 */
    private static final String NULLSTR = "";
    /**
     * 从csv读取文件并返回字符串数组类型列表
     */
    public static List<String[]> readFromCsvFile(String filePath) {
        try {
            List<String[]> csvList = new ArrayList<String[]>();
            CsvReader reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
            reader.readHeaders(); //跳过表头,不跳可以注释掉

            while (reader.readRecord()) {
                csvList.add(reader.getValues()); //按行读取，并把每一行的数据添加到list集合
            }
            reader.close();
            log.info("读取的行数：{}", csvList.size());
            log.info("读取的数据列表：{}", csvList);
            return csvList;
        } catch (Exception e) {
            log.error("从csv文件读取数据失败->{}", e.getMessage());
        }
        return null;
    }

    /**
     * 下划线转驼峰，正规的，例如flow_no->flowNo
     */
    public static String underlineToCamel(String underlineWord, boolean smallCamel) {
        if (underlineWord == null || "".equals(underlineWord)) {
            return "";
        } else if (underlineWord.length() == underlineWord.replace("_", "").length()) {
            return underlineWord;
        }
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher = pattern.matcher(underlineWord);
        matcher.find();
        String group = matcher.group();
        String head = group.substring(0, group.lastIndexOf('_'));
        pattern = Pattern.compile("(_)([A-Za-z\\d]+)?");
        matcher = pattern.matcher(underlineWord);
        while (matcher.find()) {
            String word = matcher.group();
            int index = word.lastIndexOf('_');

            if (index == 0) {
                sb.append(String.valueOf(word.charAt(1)).toUpperCase().concat(word.substring(2).toLowerCase()));
            } else {
                sb.append(word.substring(0).toLowerCase());
            }
        }

        sb.insert(0, head);
        return sb.toString();
    }

    /**
     * 从csv文件读取数据并下划线转驼峰
     */
    public static void readFromCsvFileAndUnderlineToCamel(String filePath) {
        try {
            List<String> csvList = new ArrayList<>();
            CsvReader reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
            reader.readHeaders(); //跳过表头,不跳可以注释掉

            while (reader.readRecord()) {
                String camelWord = underlineToCamel(reader.getValues()[0], false);
                csvList.add(camelWord); //按行读取，并把每一行的数据添加到list集合
            }
            reader.close();
            log.info("需要转化的数据个数：{}", csvList.size());
            log.info("转化后的数据列表：{}", csvList);
        } catch (Exception e) {

        }
    }

    /**
     * 26个引文单词组成的单词首字母大写转化
     * 场景：辅助字节码插桩技术生成实体getset方法
     * 遗留拓展点：判断一串字符呢，暴力：遍历每个字符分别判断 其他：？？？
     */
    public static String firstCharToUpCaseForWord(String originalWord) {
        if (StringUtils.isEmpty(originalWord)) {
            throw new RuntimeException("字符串为空");
        }

        char firstChar = originalWord.charAt(0);
        /**
         * 匹配65-90 97-122
         * 分析：
         * 65 - 69     6[5-9]
         * 70 - 89     [7-8][0-9]
         * 90          90
         * 97 - 99     9[7-9]
         * 100 - 119   1[0-1][0-9]
         * 120 - 122   12[0-2]
         * */
        String format = "(6[5-9])|([7-8][0-9])|(90)|(9[7-9])|(1[0-1][0-9])|(12[0-2])";
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(String.valueOf((int) firstChar));
        if (!matcher.matches()) {
            throw new RuntimeException("非26英文字母组成的单词");
        }
        /**
         * 97-122   65-90
         * [A - Z] [a - z]
         * */
        int i = firstChar - 32;
        String firstCharUpCaseWord = null;

        if (i >= 65 && i <= 90) {
            firstCharUpCaseWord = originalWord.substring(0, 1).toUpperCase().concat(originalWord.substring(1));
            System.out.println(firstCharUpCaseWord);
            log.info("{{}}--->{{}}转化成功", originalWord, firstCharUpCaseWord);
            return firstCharUpCaseWord;
        } else {
            log.info("{{}}无需转化----", originalWord);
            return originalWord;
        }
    }

    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
     *
     * @param str 指定字符串
     * @param strs 需要检查的字符串数组
     * @return 是否匹配
     */
    public static boolean matches(String str, List<String> strs)
    {
        if (isEmpty(str) || isEmpty(strs))
        {
            return false;
        }
        for (String testStr : strs)
        {
            /*if (matches(str, testStr))
            {
                return true;
            }*/
        }
        return false;
    }

    /**
     * * 判断一个字符串是否为空串
     *
     * @param str String
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(String str)
    {
        return isNull(str) || NULLSTR.equals(str.trim());
    }

    /**
     * * 判断一个Collection是否为空， 包含List，Set，Queue
     *
     * @param coll 要判断的Collection
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(Collection<?> coll)
    {
        return isNull(coll) || coll.isEmpty();
    }

    /**
     * * 判断一个对象是否为空
     *
     * @param object Object
     * @return true：为空 false：非空
     */
    public static boolean isNull(Object object)
    {
        return object == null;
    }


    public static void main(String[] args) {
        String filePath = "D:\\development\\environment\\idea\\IdeaProjects\\xlh_osms\\common\\infrastructure\\src\\main\\resources\\walletInfoDO.csv";
        readFromCsvFile(filePath);
        //readFromCsvFileAndUnderlineToCamel(filePath);
        //firstCharToUpCaseForWord("Abc");
    }
}
